package org.umss.fixturebuilder.controller;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Result;
import static org.umss.fixturebuilder.builder.data.OfyService.ofy;
import org.umss.fixturebuilder.model.appengine.ChampionshipModel;
import org.umss.fixturebuilder.model.appengine.GameModel;
import org.umss.fixturebuilder.model.appengine.TeamModel;
import org.umss.fixturebuilder.model.appengine.TeamPosition;
import org.umss.fixturebuilder.scoreboard.ScoreBoardPositionCalculator;

/**
 *
 * @author Daniela Meneses
 */
public class GameController {

    public static boolean setGameScore(String id, int localScore, int visitorScore) {
        Key<GameModel> gameKey = Key.create(id);
        Key<ChampionshipModel> championshipKey = gameKey.getParent().getParent().getParent();
        GameModel game = ofy().load().type(GameModel.class).filterKey(gameKey).first().now();
        game.setTerminated(true);
        game.setLocalScore(localScore);
        game.setVisitorScore(visitorScore);
        Result<Key<GameModel>> entity = ofy().save().entity(game);
        TeamModel localTeam = ofy().load().type(TeamModel.class).ancestor(championshipKey).filterKey(game.getLocal()).first().now();
        TeamModel visitorTeam = ofy().load().type(TeamModel.class).ancestor(championshipKey).filterKey(game.getVisitor()).first().now();
        TeamPosition localPosition = ofy().load().type(TeamPosition.class).ancestor(championshipKey).filter("teamName", localTeam.getName()).first().now();
        TeamPosition visitorPosition = ofy().load().type(TeamPosition.class).ancestor(championshipKey).filter("teamName", visitorTeam.getName()).first().now();
        ScoreBoardPositionCalculator.calculateResults(game, localPosition, visitorPosition);
        ofy().save().entity(localPosition);
        ofy().save().entity(visitorPosition);
        
        return entity != null;
    }

}
